var pattern = new RegExp(/\?DocEntry=(\S*)/g);
var idx = pattern.exec(window.location.href);
var CRM000202 = [];

var DocEntry = $('input[data-field="ItemDocEntry"]'),
    DocDate = $('input[data-field="ItemDocDate"]'),
    DocStatus = $('input[data-field="ItemDocStatus"]'),
    DocType = $('input[data-field="ItemDocType"]'),
    Title = $('input[data-field="ItemTitle"]'),
    Address = $('input[data-field="ItemAddress"]'),
    StartDate = $('input[data-field="ItemStartDate"]'),
    StartTime = $('input[data-field="ItemStartTime"]'),
    EndDate = $('input[data-field="ItemEndDate"]'),
    EndTime = $('input[data-field="ItemEndTime"]'),
    CardCode = $('input[data-field="ItemCardCode"]'),
    CardName = $('input[data-field="ItemCardName"]'),
    Contacts = $('input[data-field="ItemContacts"]'),
    Phone = $('input[data-field="ItemPhone"]'),
    Remark = $('input[data-field="ItemRemark"]'),
    grid02 = $('#jgTable02'),
    grid0m = $('#jgTable0m'),
    grid0s = $('#jgTable0s');

$(function(){
    requestAjax();
    requestSelect();
    gridInit02();
    gridInit0m();
    $("li[data-opt='add']").on('click', addCode);
    $("li[data-opt='back']").on('click', back); 
    $("#BrandBtn").on('click', addRows);
    $(".input-exp i").on('click', add0s);
    $("#js_submit, li[data-opt='save']").on("click", saveSubmit); 
    $('.modal-data').draggable();
});

//CRM000203
function requestAjax(){
    if(idx){
        var _postData = Object.create(postData);    //请求头
        _postData.Method = 'Q';
        _postData.Content = {
            "DocEntry": idx[1]
        }
        $.ajax({
            async: false,
            type: 'post', 
            url: crmPath + '/CRM0002/CRM000203',
            data: _postData,
            dataType: 'json',
            success: function (re) {
                loadAjax(re);
            }
        });        
    }  
};
function loadAjax(re){
    if(re.Status==200){
        console.log(re.Content)
        DocEntry.val(re.Content.DocEntry);
        DocDate.val(re.Content.DocDate);
        DocStatus.val(re.Content.DocStatus);
        DocType.val(re.Content.DocType);
        Title.val(re.Content.Title);
        Address.val(re.Content.Address);
        StartDate.val(new Date(re.Content.StartDate).format("yyyy-MM-dd"));
        StartTime.val(re.Content.StartTime);
        EndDate.val(new Date(re.Content.EndDate).format("yyyy-MM-dd"));
        EndTime.val(re.Content.EndTime);
        CardCode.val(re.Content.CardCode);
        CardName.val(re.Content.CardName);
        Contacts.val(re.Content.Contacts);
        Phone.val(re.Content.Phone);
        Remark.val(re.Content.Remark);
        CRM000202 = re.Content.CRM000202;
        $("#createDate").val(re.Content.CreateDate);    //
        $("#updateDate").val(re.Content.UpdateDate);    //
        $("#createUser").val(re.Content.CreateUser);    //
        $("#updateUser").val(re.Content.UpdateUser); 
    } else if (re.Status == -999) {
        alert_QX($('body'), re.Message);
    } else {
        myAlert(re.Message);
    }
}

//MDM001402
function requestSelect(){
    var postData0s = {
        Method: 'Q',
        Content: {
            SearchText: ''
        }
    }
    for(i in postData){
        postData0s[i] = postData[i]
    }
    var gridData0s = Object.create(gridData);
    gridData0s.grid = $('#jgTable0s');
    gridData0s.pager = $('#jgPager0s');
    gridData0s.url = mdmPath + '/MDM0014/MDM001402';
    gridData0s.height = '390px';
    gridData0s.colModel = [
        {label:'客户代码', name:'Code'},
        {label:'客户名称', name:'Name'}
    ];
    gridData0s.sortname = 'Code';
    gridData0s.beforeRequest = function(){
        gridData0s.grid.jqGrid("setGridParam", {
            postData : postData0s,
        });
    };
    gridData0s.loadComplete = function(xhr){
        $("li[data-opt='opt_search']").find(">i").unbind('click').bind('click', function () {
            postData.Content.SearchText = $("#opt_search").find(">input").val();
            gridData0m.grid.trigger("reloadGrid");
        });
    }
    gridData0s.multiselect = true;
    gridInit(gridData0s);    
}

//MDM000102
function gridInit0m(){
    var postData0m = {
        Method: 'Q',
        Content: {
            SearchText: ''
        }
    }
    for(i in postData){
        postData0m[i] = postData[i]
    }
    var gridData0m = Object.create(gridData);
    gridData0m.grid = $('#jgTable0m');
    gridData0m.pager = $('#jgPager0m');
    gridData0m.url = mdmPath + '/MDM0001/MDM000102';
    gridData0m.height = '390px';
    gridData0m.colModel = [
        {label:'代码', name:'Code'},
        {label:'名称', name:'Name'}
    ];
    gridData0m.sortname = 'Code';
    gridData0m.beforeRequest = function(){
        gridData0m.grid.jqGrid("setGridParam", {
            postData : postData0m,
        });
    };
    gridData0m.loadComplete = function(xhr){
        $("li[data-opt='opt_search']").find(">i").unbind('click').bind('click', function () {
            postData.Content.SearchText = $("#opt_search").find(">input").val();
            gridData0m.grid.trigger("reloadGrid");
        });
    }
    gridData0m.multiselect = true;
    gridInit(gridData0m);
}

//CRM000202
function alarmFormatter(cellvalue, options, rowdata){
    var grid = $(this);
    if(JSON.stringify(rowdata)!=='{}'){
        cellvalue = '<a href="javascript:0" opt-data="'+grid[0].id+'_delete" title="删除"><i class="fa fa-trash-o"></i></a>';
    }else{
        cellvalue = '';
    }
    return cellvalue;
}
function gridInit02(){
    var gridData02 = Object.create(gridData);
    gridData02.grid = $('#jgTable02');
    gridData02.pager = $('#jgPager02');
    gridData02.datatype = "local";
    gridData02.rowNum = '100000';
    gridData02.colModel = [
        {label:'单号', name:'DocEntry', hidden:true},
        {label:'行号', name:'LineID', hidden:true},
        {label:'排序行号', name:'OrderById', hidden:true},
        {label:'参与人工号', name:'EmployeeNo'},
        {label:'参与人姓名', name:'Employee'},
        {label:'操作', name:'Options', width:40, formatter:alarmFormatter, sortable:false}
    ];
    gridData02.beforeRequest = function(){
        gridData02.grid.jqGrid("setGridParam", {
            data : CRM000202,
        });
    };
    gridData02.loadComplete = function(xhr){
        gridSize();
        var rowData = gridData02.grid.jqGrid("getRowData");
        $('a[opt-data="jgTable02_delete"]').unbind('click').bind('click',function(){
            var rowId = $(this).parent().parent()[0].id;
            gridData02.grid.jqGrid("delRowData",rowId);
            CRM000202.forEach(function(v,i,a){
                v.EmployeeNo===rowData[rowId-1].EmployeeNo&&CRM000202.splice(i,1);
            });
            console.log(CRM000202)
        });
    };
    gridInit(gridData02);
}

//Options
function addCode(){
    window.open('CRM000202.html', '_blank');     
}
function back(){
    window.open('CRM000201.html', '_self');
}
function addRows(){
    $('#Modal02').removeClass('hidden');
    gridSize();
    $('#addBtn').unbind('click').bind('click', function(){
        var rowIds = grid0m.jqGrid('getGridParam', 'selarrrow');
        for(var arr=[],i=0;i<rowIds.length;i++){
            var addRowData = grid0m.jqGrid("getRowData",rowIds[i]);	//这是获得 某一行的数据
            CRM000202.push({EmployeeNo:addRowData.Code, Employee:addRowData.Name});
        }
        CRM000202 = CRM000202.unique('EmployeeNo');
        grid02.jqGrid("clearGridData").trigger("reloadGrid");
        $('#Modal02').addClass('hidden');
    });
}
function add0s(){
    $('#Modal0s').removeClass('hidden');
    gridSize();
    $('#addBtn2').unbind('click').bind('click', function(){
        var rowIds = grid0s.jqGrid('getGridParam', 'selarrrow');
        // console.log(rowIds)
        var addRowData = grid0s.jqGrid("getRowData",rowIds[0]);	//这是获得 某一行的数据
        // console.log(addRowData)
        CardCode.val(addRowData.Code);
        CardName.val(addRowData.Name);
        $('#Modal0s').addClass('hidden');
        grid0s.jqGrid("clearGridData").trigger("reloadGrid");
    });
}
function saveSubmit(){  //CRM000201
    var requestData = {
        Content: {
            DocEntry: DocEntry.val(),   
            DocDate: DocDate.val(),
            DocStatus: DocStatus.val(),
            DocType: DocType.val(),
            Title: Title.val(),
            Address: Address.val(),
            StartDate: StartDate.val(),
            StartTime: StartTime.val(),
            EndDate: EndDate.val(),
            EndTime: EndTime.val(),
            CardCode: CardCode.val(),
            CardName: CardName.val(),
            Contacts: Contacts.val(),
            Phone: Phone.val(),
            Remark: Remark.val(),
            CRM000202: CRM000202
        },
    }
    if(idx){
        requestData.Method = 'U'
    }else {
        requestData.Method = 'A';
        requestData.Content.DocEntry = '0';
        requestData.Content.DocDate = new Date().format("yyyy-MM-dd hh:mm:ss");
    }
    for(i in postData){
        requestData[i] = postData[i]
    }
    console.log(requestData);
    $.ajax({
        type: "post",
        url: crmPath + '/CRM0002/CRM000201',
        data: requestData,
        dataType: "json",
        success: function(re) {
            if(re.Status==200){
                myAlert('保存成功')
            }else{
                myAlert(re.Message)
            }
        }
    });   
}

//Style
function gridSize(){
    grid02.setGridWidth($('.u_tabs_container').width() - 30);
    grid0m.setGridWidth($('.u_modal_body').width());
    grid0s.setGridWidth($('.u_modal_body').eq(1).width());
}

